<?php

/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 16/8/11
 * Time: 18:05
 */
namespace app\common\util\excel;

require_once APP_PATH . '../lib/phpexcel/PHPExcel.php';

class SimpleExcel
{

    public static function output($filename, $rows, $exportOptions, $savefile = '')
    {
        $exportTitles = $exportOptions['titles'];
        $exportFields = $exportOptions['fields'];
        $exportImages = !empty($exportOptions['images']) ? $exportOptions['images'] : [];
        $options = !empty($exportOptions['options']) ? $exportOptions['options'] : [];
        $objPHPExcel = new \PHPExcel();
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("yxdsuper")
            ->setLastModifiedBy('yxdsuper')
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");


        // Add some data
        $sheet = $objPHPExcel->setActiveSheetIndex(0);
        $sheet->setTitle($filename);
        $start = ord('A');
        foreach ($exportTitles as $title) {
            $sheet->setCellValue(chr($start) . '1', $title);
            $start++;
        }
        $rowIndx = 2;
        foreach ($rows as $row) {
            $start = ord('A');
            foreach ($exportFields as $field) {
                if (isset($row[$field])) {
                    $v = $row[$field];
                    if (in_array($field, $exportImages)) {
                        $path = APP_PATH . '../public' . $v;
                        if (file_exists($path) && is_file($path)) {
                            $img = new \PHPExcel_Worksheet_Drawing();
                            $img->setPath($path);
                            $img->setHeight(50);
                            $img->setCoordinates(chr($start) . $rowIndx);
                            $img->setWorksheet($sheet);
                        }
                    } else {
                        if (isset($options[$field])) {
                            $v = isset($options[$field][$v]) ? strip_tags($options[$field][$v]) : $v;
                        }
                        $sheet->setCellValue(chr($start) . $rowIndx, $v);
                    }
                }
                $start++;
            }
            $rowIndx++;
        }
        $objPHPExcel->setActiveSheetIndex(0);
        \PHPExcel_Shared_Font::setAutoSizeMethod(\PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
        $cols = explode(":", trim(preg_replace('/\d+/u', '', $objPHPExcel->getActiveSheet()->calculateWorksheetDimension())));
        $col = $cols[0]; //first util column with data
        $end = ++$cols[1]; //last util column with data +1, to use it inside the WHILE loop. Else, is not going to use last util range column.
        while ($col != $end) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
            $col++;
        }
        // Redirect output to a client’s web browser (Excel5)
        if (empty($savefile)) {
            header("Content-type:application/vnd.ms-excel");  //设置内容类型
            header("Content-Disposition:attachment;filename=$filename.xls");  //文件下载
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
        } else {
            //We get the util used space on worksheet. Change getActiveSheet to setActiveSheetIndex(0) to choose the sheet you want to autosize. Iterate thorugh'em if needed.
            //We remove all digits from this string, which cames in a form of "A1:G24".
            //Exploding via ":" to get a 2 position array being 0 fisrt used column and 1, the last used column.
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save($savefile);

        }
        return true;
    }
}